<template>
  <div class='container' ref="container">
    <!-- 主体内容 -->
    <el-card>
      <!-- 面包屑导航 -->
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>{{queryId? '试题修改':'试题录入'}}</el-breadcrumb-item>
      </el-breadcrumb>
      <el-divider></el-divider>
      <!-- 表单内容 -->
      <el-form
      :model="qNFrom"
      ref="qNFromRef"
      :rules="qNRules"
      label-width="80px"
      >
        <!-- 学科 -->
        <el-form-item label="学科 :" prop="subjectCon">
          <el-select
          class="el-input-width"
          v-model="qNFrom.subjectCon"
          placeholder="请选择"
          @change="subjectSelected">
            <el-option
              v-for="(item,i) in subjectList"
              :key="i"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 目录 -->
        <el-form-item label="目录 :" prop="catalogCon">
          <el-select
          :disabled="isCatalogAndTag"
          class="el-input-width"
          v-model="qNFrom.catalogCon"
          placeholder="请选择">
            <el-option
              v-for="item in catalogList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 企业 -->
        <el-form-item label="企业 :" prop="companyCon">
          <el-select class="el-input-width" v-model="qNFrom.companyCon" placeholder="请选择">
            <el-option
              v-for="item in companyList"
              :key="item.number"
              :label="item.shortName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 城市 -->
        <div>
          <el-form-item label="城市 :" prop="cityCon" class="inline">
            <el-select v-model="qNFrom.cityCon" placeholder="请选择" @change="selectedCity">
              <el-option
                v-for="(item,index) in cityList[0]"
                :key="index"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label-width="5px" label="" prop="regionCon" class="inline">
            <el-select v-model="qNFrom.regionCon" :disabled="isRegion" placeholder="请选择">
              <el-option
                v-for="(item,index) in regionList"
                :key="index"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </div>

        <!-- 方向 -->
        <el-form-item label="方向 :" prop="directionCon">
          <el-select class="el-input-width" v-model="qNFrom.directionCon" placeholder="请选择">
            <el-option
              v-for="(item,index) in directionList"
              :key="index"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 题型 -->
        <el-form-item label="题型 :">
          <el-radio-group v-model="qNFrom.questionTypeCon" @change="questionTypeChange">
            <el-radio
            v-for="(item,index) in questionType"
            :key="index"
            :label="item.label"
            :value="item.value"
            ></el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 困难 -->
        <el-form-item label="困难 :">
          <el-radio-group v-model="qNFrom.difficultyCon">
            <el-radio
            v-for="(item,index) in difficulty"
            :key="index"
            :label="item.label"
            :value="item.value"
            ></el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 题干 -->
        <el-form-item label="题干 :" prop="quillTitleContent">
          <quill-editor
            v-model="qNFrom.quillTitleContent"
            ref="myQuillEditor"
            :options="editorOption"
          ></quill-editor>
        </el-form-item>

        <!-- 选项 -->
        <el-form-item v-show="!isJianDa" label="单选项 :" v-if="isRadioOrChecked">
          <el-radio-group class="sele-radio-group" v-model="radioSeleCode">
            <el-radio
            class="radio-input"
            v-for="(item,index) in qNFrom.options"
            :key="item.code"
            :label="item.code"
            @change="radioChange(item)"
            >
              {{item.code}}: <el-input v-model="item.title" placeholder="请输入内容"></el-input>
              <!-- 缩略图 -->
              <el-upload
                ref="uploads"
                class="avatar-uploader disabled"
                action="#"
                list-type="picture-card"
                :auto-upload="false"
                :on-change="(file)=>{loadQuestImg(file,item)}"
                :limit="1"
                :file-list="fileList"
                >
                  <i slot="default" class="el-icon-plus"></i>
                  <template slot="file" slot-scope="{file}">
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url" alt=""
                    >
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                      >
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleRemove(file,index)"
                      >
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </template>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
              <!-- /缩略图 -->
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 多选选项模板 -->
        <el-form-item v-show="!isJianDa" v-if="!isRadioOrChecked" label="多选项 :">
          <el-checkbox-group class="sele-radio-group" v-model="checkedSeleCode">
            <el-checkbox
            class="radio-input"
            v-for="(item,index) in qNFrom.checkedOptions"
            :key="item.code"
            :label="item.code"
            @change="checkedChange(item)"
            >
              {{item.code}}: <el-input v-model="item.title" placeholder="请输入内容"></el-input>
              <!-- 缩略图 -->
              <el-upload
                ref="uploads"
                class="avatar-uploader disabled"
                action="#"
                list-type="picture-card"
                :auto-upload="false"
                :on-change="(file)=>{loadQuestImg(file,item)}"
                :limit="1"
                :file-list="fileList"
                >
                  <i slot="default" class="el-icon-plus"></i>
                  <template slot="file" slot-scope="{file}">
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url" alt=""
                    >
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                      >
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleRemove(file,index)"
                      >
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </template>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
              <!-- /缩略图 -->
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- 选项中的添加按钮 -->
        <el-button
         v-if="!isJianDa"
        class="el-my-btn"
        :disabled="isAddQuestSeleBtn"
        type="danger"
        @click="addSeleAndQuest"
        >+添加选项与答案</el-button>

        <!-- 解析视频 -->
        <el-form-item class="video-item" label="解析视频 :">
          <el-input class="el-input-width" v-model="qNFrom.videoCon"></el-input>
        </el-form-item>

        <!-- 答案解析 -->
        <el-form-item class="video-item" label="答案解析 :" prop="quillAnswerContent">
          <quill-editor
            v-model="qNFrom.quillAnswerContent"
            ref="myQuillEditor"
            :options="editorOption"
          ></quill-editor>
        </el-form-item>

        <!-- 题目备注 -->
        <el-form-item class="video-item" style="margin-top: 50px;" label="题目备注 :">
          <el-input
            class="el-input-width"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="请输入内容"
            v-model="qNFrom.textarea"
            maxlength="30"
            show-word-limit
          >
          </el-input>
        </el-form-item>

        <!-- 试题标签 -->
        <el-form-item label="试题标签 :">
          <!-- 多选下拉 -->
          <el-select
          :disabled="isCatalogAndTag"
          class="el-input-width"
          v-model="qNFrom.questTagCon"
          placeholder="请选择"
          multiple
          >
            <el-option
              v-for="item in questTagList"
              :key="item.id"
              :label="item.tagName"
              :value="item.tagName">
            </el-option>
          </el-select>
        </el-form-item>

        <el-button @click="onSubmit" class="el-my-btn" :type="queryId ? 'success':'primary'">{{queryId ? '提交修改' : '确认提交'}}</el-button>

      </el-form>
    </el-card>
  </div>
</template>

<script>
// 导入富文本插件
import { quillEditor } from 'vue-quill-editor' // 调用编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

// 导入下拉框数据请求相关模板
import { simple } from '@/api/hmmm/subjects'
import { list as comList } from '@/api/hmmm/companys'
import { simple as dirList } from '@/api/hmmm/directorys'
import { list as tagList } from '@/api/hmmm/tags'
import { list as questList, add, update, choice } from '@/api/hmmm/questions'

// 导入静态数据
import { provinces, citys, findProv } from '@/api/hmmm/citys'
import { direction, difficulty, questionType } from '@/api/hmmm/constants'
export default {
  props: ['file'],
  name: 'QuestionsNew',
  components: {
    quillEditor
  },
  data () {
    return {
      qNFrom: {
        subjectCon: '', // 学科 id
        catalogCon: '', // 目录 str
        companyCon: '', // 企业 str
        cityCon: '', // 城市 str
        regionCon: '', // 地区 str
        directionCon: '', // 方向 str
        questTagCon: [], // 试题标签
        videoCon: '', // 视频解析
        quillTitleContent: '', // 题干富文本
        quillAnswerContent: '', // 答案富文本
        textarea: '', // 题目备注
        questionTypeCon: '单选', // 题型单选
        difficultyCon: '简单', // 困难单选
        options: [ // 单选项数据
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ],
        checkedOptions: [ // 多选项数据
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ]
      },
      qNRules: {
        subjectCon: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        catalogCon: [

        ],
        companyCon: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        cityCon: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        regionCon: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        directionCon: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        quillTitleContent: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        quillAnswerContent: [
          { required: true, message: '必填项', trigger: 'blur' }
        ]
      },
      cityList: [],
      regionList: [],
      isRegion: true,
      directionList: [],
      subjectList: [],
      catalogList: [],
      isCatalogAndTag: true,
      companyList: [],
      questTagList: [],
      isAddQuestSeleBtn: true,
      isJianDa: false,
      isRadioOrChecked: true,
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      radioSeleCode: '',
      checkedSeleCode: [],
      fileList: [],
      editorOption: {
        placeholder: '请在这里输入',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            ['blockquote', 'code-block'], // 引用，代码块
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['image', 'link'] // 上传图片、上传视频
          ]
        }
      }
    }
  },
  computed: {
    // 题型单选数组
    questionType () {
      return questionType
    },
    // 困难单选数组
    difficulty () {
      return difficulty
    },
    // 判断是否有id，如果有传个id，如果没有传个 false
    queryId () {
      return this.$route.query.id
    },
    isChoiceOrPutong () {
      return localStorage.getItem('requestType')
    }
  },
  // 路由守卫
  beforeRouteEnter (to, from, next) {
    if (from.name === 'questions-choice') {
      localStorage.setItem('requestType', 'choice')
    } else {
      localStorage.setItem('requestType', 'questions')
    }
    next()
  },
  created () {
    // 初始化城市下拉框
    this.loadCity()
    // 初始化方向下拉框
    this.directionList = direction
    // 初始化学科下拉框
    this.loadSubject()
    // 初始化企业下拉框
    this.loadCompany()

    // 判断是否有其他题库中传递的id
    if (this.queryId) {
      // console.log('有id', this.queryId)
      this.loadQuestList(this.queryId)
      // 打开目录
      this.isCatalogAndTag = false
      this.qNRules.catalogCon.push({ required: true, message: '必填项', trigger: 'blur' })

      // 手动启用城市地区下拉
      this.isRegion = false
    }
  },
  mounted () {
    this.$refs.myQuillEditor.quill.enable(false)
  },
  methods: {
    // 请求并渲染目录数据
    async loadDirList (subjectID) {
      try {
        const { data: res } = await dirList({ subjectID })
        if (!res.length) {
          this.isCatalogAndTag = true
          this.qNRules.catalogCon = []
        } else {
          this.qNRules.catalogCon.push({ required: true, message: '必填项', trigger: 'blur' })
        }
        this.catalogList = res
      } catch (error) {
        console.error(error)
      }
    },
    // 请求并渲染标签数据
    async loadTagList (subjectID) {
      try {
        const { data: res } = await tagList({ subjectID })
        this.questTagList = res.items
      } catch (error) {
        console.error(error)
      }
    },
    // 加载学科下拉数据事件
    async loadSubject (id) {
      try {
        const { data: res } = await simple()
        this.subjectList = res
      } catch (error) {
        console.error(error)
      }

      // if (id) { // id - queryId
      //   // 16 - 大数据
      //   const item = this.subjectList.find(t => t.value === parseInt(id))
      //   this.qNFrom.subjectCon = item.label
      // }
    },
    // 监听学科下拉框的选择
    subjectSelected (val) {
      this.qNFrom.catalogCon = ''
      this.isCatalogAndTag = false
      // const item = this.subjectList.find(t => t.value === val)
      // 请求目录数据并初始化
      this.loadDirList(val)
      // 请求试题标签数据并初始化
      this.loadTagList(val)
    },
    // 加载企业下拉数据事件
    async loadCompany () {
      try {
        const { data: res } = await comList({ pagesize: 20 })
        this.companyList = res.items
      } catch (error) {
        console.error(error)
      }
      // 成功...
    },
    // 加载城市下拉数据事件
    loadCity () {
      this.cityList.push(provinces())
    },
    // 当城市第一项的选择项发生改变时事件
    selectedCity (val) {
      this.qNFrom.regionCon = ''
      this.isRegion = false
      // 加载城市下地区下拉数据
      // 在选择了城市后调用该方法 - 监听城市选择下拉框的 change 事件来发生改变
      this.regionList = citys(val)
    },
    // 监听题型单选改变事件
    questionTypeChange (val) {
      // isRadioOrChecked false - 关闭   true - 打开
      // isAddQuestSeleBtn： false - 打开   true - 关闭
      if (val === '多选') {
        this.isRadioOrChecked = false
        this.isAddQuestSeleBtn = false
        this.isJianDa = false
      } else if (val === '单选') {
        this.isRadioOrChecked = true
        this.isAddQuestSeleBtn = true
        this.isJianDa = false
      } else {
        this.isJianDa = true
      }
    },
    radioChange (item) {
      // 先将所有 isRight 变为 false
      this.qNFrom.options.forEach(t => { t.isRight = false })
      // 问题：延时改变了 isRight
      // 开启新的true
      item.isRight = true
    },
    checkedChange (item) {
      item.isRight = !item.isRight
    },
    handleRemove (file, index) {
      const fileList = this.$refs.uploads[index].uploadFiles
      fileList.splice(fileList.indexOf(file), 1)
      // 清除 img 数据
      // const item = this.qNFrom.options.find(t => t.img === file.url)
      this.qNFrom.options[index].img = ''
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    loadQuestImg (file, item) {
      item.img = file.url
    },
    // 提交请求
    async resquestData (data) {
      try {
        await add(data)
      } catch (error) {
        console.error(error)
      }
    },
    // 点击添加新问题和答案
    addSeleAndQuest () {
      const codeStr = this.qNFrom.checkedOptions[this.qNFrom.checkedOptions.length - 1].code
      let num = codeStr.charCodeAt()
      num++
      // console.log(String.fromCharCode(num))
      if (num !== 91) {
        this.qNFrom.checkedOptions.push({
          code: String.fromCharCode(num),
          title: '',
          img: '',
          isRight: false
        })
      } else {
        console.log('添加过多')
      }
    },
    // 调用发起修改试题请求
    async editResquestData (data) {
      try {
        await update(data)
      } catch (error) {
        console.error(error)
      }
    },
    // 提交事件
    onSubmit () {
      this.$refs.qNFromRef.validate(valid => {
        if (!valid) return console.log('提交数据有问题')
        // 先处理 tags 将它变为 字符串
        const data = {
          subjectID: this.qNFrom.subjectCon, // 学科
          catalogID: this.qNFrom.catalogCon, // 目录
          enterpriseID: this.qNFrom.companyCon, // 企业
          province: this.qNFrom.cityCon, // 城市
          city: this.qNFrom.regionCon, // 地区 str
          direction: this.qNFrom.directionCon, // 方向 str
          tags: !this.qNFrom.questTagCon.length ? '无' : this.qNFrom.questTagCon.join(','), // 试题标签
          videoURL: this.qNFrom.videoCon, // 视频解析
          question: this.qNFrom.quillTitleContent, // 题干富文本
          answer: this.qNFrom.quillAnswerContent, // 答案富文本
          remarks: this.qNFrom.textarea, // 题目备注
          questionType: this.qNFrom.questionTypeCon, // 题型单选
          difficulty: this.qNFrom.difficultyCon, // 困难单选
          options: this.isRadioOrChecked ? this.qNFrom.options : this.qNFrom.checkedOptions // 选项数据
        }
        if (this.queryId) {
          // 修改试题处理
          data.id = this.qNFrom.id
          data.number = this.qNFrom.number
          data.creator = this.qNFrom.creator
          data.addDate = this.qNFrom.addDate
          console.log(data)

          // 修改请求
          this.editResquestData(data)
          return
        }
        // 新增请求
        this.resquestData(data)
      })
    },
    // 传入 id 时根据试题列表 id 渲染整个页面内容
    async loadQuestList (id) {
      // const { data: res } = await questList({ pagesize: 20 })
      // const resItem = res.items.find(t => t.id === parseInt(id))
      let resItem
      if (this.isChoiceOrPutong === 'choice') {
        const { data: res } = await choice({ pagesize: 20 })
        resItem = res.items.find(t => t.id === parseInt(id))
      } else {
        const { data: res } = await questList({ pagesize: 20 })
        resItem = res.items.find(t => t.id === parseInt(id))
      }
      // console.log('res', res)
      // console.log(resItem)

      this.qNFrom = {
        subjectCon: resItem.subjectID, // 学科
        catalogCon: resItem.catalogID, // 目录
        companyCon: resItem.enterpriseID, // 企业
        cityCon: resItem.province ? resItem.province : findProv(resItem.city), // 手动通过城市地区找到城市
        regionCon: resItem.city, // 地区 str
        directionCon: resItem.direction, // 方向 str
        questTagCon: resItem.tags.split(','), // 试题标签
        videoCon: resItem.videoURL, // 视频解析
        quillTitleContent: resItem.question, // 题干富文本
        quillAnswerContent: resItem.answer, // 答案富文本
        textarea: resItem.remarks, // 题目备注
        questionTypeCon: resItem.questionType, // 题型单选
        difficultyCon: resItem.difficulty, // 困难单选
        checkedOptions: this.qNFrom.options,
        options: this.qNFrom.checkedOptions,
        // 其他修改需要参数
        addDate: resItem.addDate,
        creator: resItem.creator,
        id: resItem.id,
        number: resItem.number
      }
      // 单独处理选项模块数据 - 需判断是多选还是单选
      const dongtaiOptions = resItem.options && resItem.options.length > 4 ? 'checkedOptions' : 'options'
      // console.log('dongtaiOptions', dongtaiOptions)
      // 判断响应的数据有还是没有
      this.qNFrom[dongtaiOptions] = resItem.options ? resItem.options : this.qNFrom[dongtaiOptions]
      // console.log(this.qNFrom[dongtaiOptions])

      // 手动调用 渲染目录列表
      this.loadDirList(resItem.subjectID)

      // 手动获取城市地区列表
      this.regionList = citys(this.qNFrom.cityCon)

      // 手动打开选项模块
      this.questionTypeChange(resItem.questionType)

      // 富文本编辑器神坑处理
      this.$nextTick(function () {
        this.$refs.myQuillEditor.quill.enable(true)
        this.$refs.myQuillEditor.quill.blur()
        console.log(this.$refs.container)
        window.scrollTo(0, 0)
      })
    }
  }
}
</script>

<style scoped lang='less'>
.container {
  padding: 10px;
  .radio-input {
    margin-top: 10px;
  }
  .sele-radio-group {
    width: 400px;
  }
  .avatar-uploader {
    display: inline-block;
    border: 1px dotted #d9d9d9;
    border-radius: 3px;
    cursor: pointer;
    position: relative;
    width: 70px;
    height: 50px;
    margin-left: 5px;
    line-height: 48px;
    text-align: center;
    vertical-align: middle;
  }
  /deep/ .el-upload {
    width: 70px;
    height: 50px;
    position: relative;
    .el-icon-plus {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
    }
  }
  // /deep/ .disabled .el-upload--picture-card {
  //   display: none;
  // }
  /deep/ .el-upload-list__item {
    width: 70px;
    height: 50px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-text {
    font-size: 12px;
    color: #8c939d;
    text-align: center;
  }
  .right-top-close {
    position:absolute;
    top: -8px;
    right: -8px;
  }
  .el-my-btn {
    margin-left: 80px;
  }
  .video-item {
    margin-top: 15px;
  }
  .el-input-width {
    width: 438px;
  }
  .quill-editor{
    height:250px;
    margin-bottom: 60px;
  }
  .inline {
    display: inline-block;
  }
}
</style>
